<template>
  <a-config-provider prefix-cls="ss">
    <div class="editing_center">
      <div class="top_bar">
        <!-- 一键成片不显示返回 -->
        <topBar
          :showSave="false"
          :showBack="!(edit_model == 2 && !fromAi)"
          @backPrevious="handleGo"
        />
      </div>
      <div class="main_con">
        <div class="left_preview_set">
          <generatePreview
            :edit_model="edit_model"
            :recordId="route.query?.id"
            :selectList="selectList"
            :dataList="resultList"
            :isAgain="isAgain"
            :numInfo="numInfo"
            :status="status"
            @blur="handleBlur"
          />
        </div>
        <div class="right_video_con">
          <div class="top_con">
            <div v-if="isAgain">
              <a-radio-group v-model:value="status" @change="handleChange">
                <a-radio-button value="all"
                  >全部 ({{ numInfo?.all }})</a-radio-button
                >
                <a-radio-button value="un_synthesized"
                  >未合成 ({{ numInfo?.un_synthesized }})</a-radio-button
                >
                <a-radio-button value="succeeded"
                  >已合成 ({{ numInfo?.success }})</a-radio-button
                >
              </a-radio-group>
            </div>
            <div>
              共有成片组合：
              <span style="color: #000; margin: 0 5px; margin-right: 20px">{{
                numInfo?.all
              }}</span>

              <div class="right_generate" v-if="generateLoading">
                <span style="--i: 1">还</span>
                <span style="--i: 2">有</span>
                <span style="--i: 3">视</span>
                <span style="--i: 4">频</span>
                <span style="--i: 5">生</span>
                <span style="--i: 6">成</span>
                <span style="--i: 7">中</span>
                <span style="--i: 8">.</span>
                <span style="--i: 9">.</span>
                <span style="--i: 10">.</span>
              </div>
            </div>
            <!-- 已按照推荐及差异度大排序 -->
          </div>
          <div class="bottom_video_con">
            <resultList
              :edit_model="edit_model"
              :dataList="resultList"
              :parentSelectList="selectList"
              :isAgain="isAgain"
              :status="status"
              @change="handleSelectChange"
              :hasMore="hasMore"
              @getMore="getMore"
            />
          </div>
        </div>
      </div>
    </div>
  </a-config-provider>
</template>

<script>
import {
  computed,
  defineComponent,
  onMounted,
  reactive,
  ref,
  toRefs,
  watch,
} from "vue";
import { useRoute, useRouter } from "vue-router";
import request from "@/common/utils/request";
import topBar from "../EditingCenter/modules/topBar/index.vue";
import generatePreview from "./modules/generatePreview/index.vue";
import resultList from "./modules/resultList/index.vue";
import { useTimeoutPoll } from "@vueuse/core";
import _ from "lodash";
import store from "../../../store";
import { ConfigProvider } from "ant-design-vue";
export default defineComponent({
  name: "EditingCenterPreview",
  components: {
    topBar,
    generatePreview,
    resultList,
  },
  setup() {
    // 配置主题色
    ConfigProvider.config({
      prefixCls: "ss",
      theme: {
        primaryColor: "#2878FF",
      },
    });
    const router = useRouter();
    const route = useRoute();
    const state = reactive({
      showResult: false,
      resultList: [],
      numInfo: {},
      edit_model: "",
      selectList: [],
      status: "un_synthesized",
      pollLoading: false,
      page: 1,
      pageSize: 10,
      hasMore: true,
      moreLoading: false,
      ids: [],
    });

    const getGeneratePreview = () => {
      request
        .get("work_ai", "/user/shotstack/clip/response/list", {
          editing_record_id: route.query?.id,
          edit_model: state.edit_model,
        })
        .then((res) => {
          if (
            res?.result?.every(
              (i) => i.status !== null && i.status !== "rendering"
            )
          ) {
            generateLoading.value = false;
            getResultList();
            state.pollLoading = false;
            pause();
          }

          // 完成的list
          const pollListIds = res?.result
            ?.filter((i) => i.status === "done")
            .map((i) => i.id);

          const resultListIds = state.resultList?.map((i) => i.id);

          const difference = _.difference(pollListIds, resultListIds);
          const isSubset = difference.length === 0;

          if (!isSubset) {
            getResultList();
          }
        })
        .catch(() => {
          state.pollLoading = false;
          generateLoading.value = false;
          pause();
        });
    };
	
	if(route.query?.edit_model){
		state.edit_model = route.query?.edit_model
	}

    const getMore = () => {
      if (state.moreLoading) {
        return;
      }

      state.moreLoading = true;
      request
        .get("work_ai", "/user/shotstack/clip/compose/detail", {
          id: route.query?.id,
          status: state.status,
          page: state.page,
          pageSize: state.pageSize,
          // pageSize: 10000,
          edit_model: state.edit_model,
        })
        .then((res) => {
          state.moreLoading = false;
          let arr = [];
          res?.result.data?.forEach((i) => {
            if (!state.ids.includes(i.id)) {
              arr.push(i);
            }
          });

          state.ids = [...new Set([...state.ids, ...arr?.map((i) => i.id)])];

          state.resultList = [...state.resultList, ...arr];

          if (res?.result?.data?.length == state.pageSize) {
            state.page += 1;
            state.hasMore = true;
          } else {
            state.hasMore = false;
          }
        })
        .catch(() => {
          state.hasMore = false;
          state.moreLoading = false;
        });
    };

    const getDetailPoll = (isFirst) => {
      if (isFirst) {
        generateLoading.value = true;
      }
      request
        .get("work_ai", "/user/shotstack/clip/compose/detail", {
          id: route.query?.id,
          status: state.status,
          page: state.page,
          pageSize: state.pageSize,
          // pageSize: 10000,
          edit_model: state.edit_model,
        })
        .then((res) => {
          let arr = [];
          res?.result.data?.forEach((i) => {
            if (!state.ids.includes(i.id)) {
              arr.push(i);
            }
          });

          state.ids = [...new Set([...state.ids, ...arr?.map((i) => i.id)])];

          state.resultList = [...state.resultList, ...arr];

          if (isFirst) {
            state.selectList = res?.result?.data
              ?.filter((i) => i.succeeded === 0)
              ?.map((i) => i.id);
          }
          state.numInfo = res?.result?.num_info;
          state.edit_model = res?.result?.edit_model;

          if (res?.result?.data?.length == state.pageSize) {
            state.hasMore = true;
          } else {
            state.hasMore = false;
          }

          if (res.result?.is_all_done === 1 || state.edit_model == 5) {
            pause();
            generateLoading.value = false;
          } else {
            if (isFirst) {
              setTimeout(() => {
                resume();
              }, 3000);
            }
          }
        })
        .catch(() => {
          pause();
          generateLoading.value = false;
          state.moreLoading = false;
        });
    };

    const { pause, resume } = useTimeoutPoll(getDetailPoll, 5000);

    // 再次剪辑
    const isAgain = computed(() => route.query?.type === "again");
    // 选择导出
    const fromAi = computed(() => route.query?.from === "ai");
    const generateLoading = ref(false);

    const getResultList = (isFirst) => {
      if (isFirst) {
        generateLoading.value = true;
      }
      request
        .get("work_ai", "/user/shotstack/clip/compose/detail", {
          id: route.query?.id,
          status: state.status,
          page: state.page,
          // pageSize: state.pageSize,
          pageSize: 10000,
          edit_model: state.edit_model,
        })
        .then((res) => {
          state.resultList = res?.result?.data;

          if (isFirst) {
            state.selectList = res?.result?.data
              ?.filter((i) => i.succeeded === 0)
              ?.map((i) => i.id);
          }
          state.numInfo = res?.result?.num_info;
          state.edit_model = res?.result?.edit_model;
          if (state.resultList?.length < res?.result.total) {
            state.hasMore = true;
          }
          isFirst && resume();
        })
        .catch(() => {
          generateLoading.value = false;
        });
    };

    const handleGo = () => {
      router.back();
    };

    const handleSelectChange = (list) => {
      state.selectList = list;
    };

    const handleBlur = (list) => {
      state.selectList = list;
    };

    const handleChange = () => {
      // getResultList();
	  state.ids = []
	  state.resultList = []
    // 设置获取页面为第一页
    state.page = 1;
      getDetailPoll();
    };

    onMounted(() => {
      if (isAgain.value) {
        state.status = "un_synthesized";
      }
    });

    onMounted(() => {
      // getResultList(true);
      getDetailPoll(true);
      // resume();
    });

    return {
      ...toRefs(state),
      route,
      fromAi,
      isAgain,
      getMore,
      handleGo,
      handleBlur,
      handleChange,
      generateLoading,
      handleSelectChange,
    };
  },
});
</script>

<style lang="less" scoped>
.editing_center {
  width: 100%;
  height: 100vh;
  background-color: #000;
  .top_bar {
    width: 100%;
    height: 60px;
  }

  .left_preview_set {
    width: 315px;
    height: 100%;
    background: #ffffff;
    box-shadow: 7px 0 7px 7px #000000;
  }
  .right_video_con {
    width: calc(100% - 315px);
    height: 100%;
    .top_con {
      height: 70px;
      background-color: #fafafa;
      display: flex;
      align-items: center;
      padding-left: 20px;
      color: #999;
      font-size: 15px;
      justify-content: space-between;
    }

    .right_generate {
      display: inline-block;
      margin-left: 20px;
      color: #2878FFff;
      > span {
        margin-top: 6px;
        display: inline-block;
        animation: dongHua 1.5s ease-in-out infinite;
        animation-delay: calc(0.1s * var(--i));
      }
    }

    @keyframes dongHua {
      0% {
        transform: translateY(0px);
      }
      20% {
        transform: translateY(-10px);
      }
      40%,
      100% {
        transform: translateY(0px);
      }
    }
    .bottom_video_con {
      height: calc(100% - 70px);
      background-color: #eee;
    }
  }

  .main_con {
    height: calc(100% - 60px);
    display: flex;

    .left_material_con {
      height: calc(100% - 20px);
      width: calc(73% - 15px);
      margin-left: 10px;
      margin-top: 10px;
    }
    .right_video_set {
      width: calc(27% - 15px);
      margin-left: 10px;
      height: calc(100% - 20px);
      margin-top: 10px;
      .video_con {
        width: 100%;
        height: 70%;
      }
      .set_con {
        width: 100%;
        height: calc(30% - 10px);
        margin-top: 10px;
      }
    }

    .left_menu {
      width: 88px;
      height: 100%;
    }
    .right_main {
      width: calc(100% - 88px);
      height: 100%;
      display: flex;
      .material_con {
        width: 318px;
        height: 100%;
      }

      .right_overview {
        width: calc(100% - 325px);
        margin-left: 7px;
        height: calc(100% - 7px);
        margin-top: 7px;
        .generate_preview {
          width: 100%;
          height: 50%;
          display: flex;
          justify-content: space-between;
          .left_preview {
            width: calc(50% - 10px);
            height: 100%;
          }
          .right_common {
            width: 50%;
            height: 100%;
            overflow-y: scroll;
            &::-webkit-scrollbar {
              width: 0px;
            }
          }
        }
        .bottom_con {
          width: 100%;
          height: calc(50% - 7px);
          margin-top: 7px;
        }
      }
    }
  }
}
</style>
